#!/bin/bash
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.

CONTAINER_PATH="$CCI_SRC/container"

source ${CCI_SRC}/lib/log.sh

build_depends()
{
	local container=$1

	for dep in $(cat $container/*-depends 2> /dev/null)
	do
		build_depends $CONTAINER_PATH/$dep &
	done
	wait

	do_one_build $container
}

do_one_build()
{
	local container=$1
	local container_name=$(basename $container)
	lockfile-create -q --use-pid --retry 100 --lock-name "build_${container_name}".lock

	mkdir $tmpdir/$container_name 2>/dev/null &&
	(
		cd "$container"
		[ -x build ] && ./build
		[ "$?" == 0 ] && log_info "finish build $container"
		[ -x install ] && ./install
	)
	lockfile-remove --lock-name "build_${container_name}".lock
}

start_depends()
{
	local container=$1

	for dep in $(cat $container/start-depends 2> /dev/null)
	do
		start_depends $CONTAINER_PATH/$dep &
	done
	wait

	do_one_run $container
}

do_one_run()
{
	local container=$1
	local container_name=$(basename $container)
	lockfile-create -q --use-pid --retry 100 --lock-name "start_${container_name}".lock

	mkdir $tmpdir/start_$container_name 2>/dev/null &&
	(
		cd "$container"
		declare -A dic
		local dic=(['ssh-r']='ssh_r' ['etcd']='etcd-server' ['rabbitmq']='rabbitmq' ['es']='es-server01' ['redis']='redis507s01' ['rpm-repo']='update-repodata')
		for item in ${!dic[@]}
		do
			[ "$container_name"  == ${item} ] && {
				container_id=$(docker ps -aqf name=${dic[${item}]})
				[ -n "$container_id" ] && exit
			}
		done
		[ -x first-run ] && ./first-run
		[ -x start ] && ./start
	)
	lockfile-remove --lock-name "start_${container_name}".lock
}

build_all()
{
	for dir in $CONTAINER_PATH/*/
	do
		build_depends $dir &
	done
	wait
}

start_all()
{
	for dir in $CONTAINER_PATH/*/
	do
		start_depends $dir &
	done
	wait
}


tmpdir=$(mktemp -d)

build_all
start_all

rm -fr $tmpdir
